/*
 *@(#)OrgasmController.java 1.0 Mar 31, 2008
 *Copyright Fution Bai
 *
 */
package codebush.web.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import codebush.service.Get;
import codebush.service.Home;
import codebush.service.Subject;
import codebush.service.Tag;
import codebush.util.HttpUtil;

/**
 * 
 * @author Fution Bai
 * @since 1.0
 */

@Controller
public class OrgasmController {

	private final Get get;

	@Autowired
	public OrgasmController(Get get) {
		this.get = get;
	}

	@RequestMapping("/index.asm")
	public String index() {
		return "index";
	}

	/**
	 * generate the verified code image
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/verifiedImage.asm")
	public void verifiedCodeImageGeneration(HttpServletRequest request, HttpServletResponse response) throws IOException {

		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		// 在内存中创建图象
		int width = 60, height = 20;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 获取图形上下文
		Graphics2D g = image.createGraphics();
		// 生成随机类
		Random random = new Random();
		// 设定背景色
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, width, height);
		// 设定字体
		g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
		// 取随机产生的认证码(4位数字)
		StringBuffer sRand = new StringBuffer("");
		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand.append(rand);
			// 将认证码显示到图象中
			g.setColor(Color.RED);
			g.drawString(rand, 13 * i + 6, 16);
		}
		// 将认证码存入SESSION
		request.getSession().setAttribute("veifiedCode", sRand.toString());
		// 图象生效
		g.dispose();
		// 输出图象到页面
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}

	/**
	 * get the user's logo image
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/uLogoPicture.asm")
	public void getUserLogoPicture(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Blob p = (Blob) this.get.getUserLogoPictureByUserId(HttpUtil.getUserId(request.getSession()));
		BufferedImage bufferedImage = ImageIO.read(p.getBinaryStream());
		ImageIO.write(bufferedImage, "JPG", response.getOutputStream());
	}
}
